$(function () {

    layui.use(['form'], function() {
        var form = layui.form();

        var initIndex = 0;

        getReviewers({});

        // 初始化页面上的 datetimepicker
        insDatetimePicker('.is-date');


        $('#add-detail-item').click(function() {
            initIndex++;

            var dom = [
                '<tr>',
                '<td class="valign-middle"></td>',
                '<td>',
                '<input type="text" name="details['+ initIndex +'][name]" lay-verify="required" class="layui-input" placeholder="供应商名称">',
                '</td>',
                '<td>',
                '<select name="details['+ initIndex +'][type]">',
                '<option value="外采" selected>外采</option>',
                '<option value="委外">委外</option>',
                '</select>',
                '</td>',
                '<td>',
                '<input type="text" name="details['+ initIndex +'][po_no]" lay-verify="required" class="layui-input" placeholder="P/O NO">',
                '</td>',
                '<td>',
                '<button type="button" class="btn btn-danger btn-sm remove-item">删除</button>',
                '</td>',
                '</tr>'
            ].join('');

            $('.cgdd-table tbody').append(dom);
            form.render();
            generateIndex();
        });

        $('.cgdd-table').on('click', '.remove-item', function() {
            var childrenLen = $('.cgdd-table tbody').children().length;
            if (childrenLen <= 1) {
                layer.msg('至少保留一项明细', {
                    icon: 0,
                    time: 2000
                });
                return false;
            }
            $(this).parent().parent().remove();
            generateIndex();
        });
    });

    function generateIndex()
    {
        $('.cgdd-table tbody tr').each(function(index) {
            $(this).find('td:first-child').text(index + 1);
        });
    }
});